package com.lanyou.esb.redis.proxy.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.lanyou.esb.common.Constants4Redis;
import com.lanyou.esb.redis.JedisPoolUtils;
import com.lanyou.esb.redis.proxy.base.BaseStrJedisProxy;
import com.lanyou.esb.redis.vo.PfThroughputVo;

/**
 * 平台吞吐量Redis操作代理
 * 
 * @author Davey.wu
 */
@Service
public class PfThroughputJedisProxy extends BaseStrJedisProxy<PfThroughputVo> {
	/** 精确到日 **/
	private static final SimpleDateFormat DATEFORMATE = new SimpleDateFormat(
			Constants4Redis.DATE_PATTERN_YYYYMMDD_NOSPACE);

	public PfThroughputJedisProxy() {
		this.setTimeOut(Constants4Redis.REDIS_TIMEOUT_PF_THROUGHPUT);
		this.setPrefix(Constants4Redis.PREFIX_PFTHROUGHPUT);
	}

	@Override
	public long setex(String key, PfThroughputVo target)
			throws JsonProcessingException {
		String result = "";
		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			// 判断是否已经存在该对象，不存在则创建
			if (jedis.get(key) == null) {
				result = jedis.set(key, toJson(target));
			}
			// 区间吞吐量增加
			jedis.incrByFloat(getQytKey(key), target.getThroughputQty());
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(result)) {
			return 0l;
		}
		if (STRING_SET_RESULT.equalsIgnoreCase(result)) {
			return 1;
		}
		return 0l;
	}

	public double getQty(String key, boolean database)
			throws JsonParseException, JsonMappingException, IOException {
 		String value ="";
 		Jedis jedis = JedisPoolUtils.getJedis();
		if (jedis == null) {
			return 0l;
		}
		boolean broken = false;
		try {
			value = jedis.get(key);
		} catch (Exception e) {
			broken = true;
		} finally {
			JedisPoolUtils.returnRes(jedis, broken);
		}
		if (StringUtils.isBlank(value)) {
			return 0;
		}
		try {
			return Double.parseDouble(value);
		} catch (Exception e) {
			return 0;
		}
	}

	@Override
	public String generateKeyFromObject(PfThroughputVo target) {
		return this.getPrefix() + KEY_SEPARATOR + target.getFieldId()
				+ KEY_SEPARATOR
				+ DATEFORMATE.format(target.getStatisticsDate());
	}

	public String getQytKey(String key) {
		return key + Constants4Redis.SUFFIX_QTY;
	}
}
